import { useRouteQuery } from '@vueuse/router'
import { isFunction } from '@/utils'
import type { AppendOption } from '@/api/helper/http'

interface TableListProps {
  apikey: string
  queryObj?: any
  immediate?: boolean
  baseConds?: Array<any>
  appendCfg?: AppendOption
  startKey?: 'start' | 'startRow'
  handleData?: (data: Array<any>) => any[] | Promise<any>
}
export function useTableList({
  apikey,
  queryObj = {},
  handleData = null,
  appendCfg = null,
  startKey = 'start',
  immediate = true,
  baseConds = [],
}: TableListProps) {
  const tableLoading = ref(false)
  const data = ref([])
  const page = useRouteQuery('page', 1, { transform: Number })
  const size = useRouteQuery('size', 20, { transform: Number })
  const total = ref(0)
  async function queryData() {
    const qobj: any = {}
    qobj.conditions = []

    // 合并查询条件
    Object.assign(qobj, unref(queryObj))
    qobj.conditions = qobj.conditions.concat(baseConds)
    if (!apikey)
      return
    // 删除最后一页一条数据
    if (data.value.length === 1 && page.value > 1) {
      page.value = page.value - 1
      return
    }
    qobj.limit = size.value

    qobj[startKey] = (page.value - 1) * size.value
    try {
      tableLoading.value = true
      const { inventories = [], total: t = 0 } = await useRequest(apikey, qobj, appendCfg)
      total.value = t
      if (handleData && isFunction(handleData))
        data.value = await handleData(inventories)
      else
        data.value = inventories
    }
    catch (e) {
      console.error(e)
    }
    finally {
      tableLoading.value = false
    }
  }

  if (immediate)
    queryData()
  return {
    tableLoading,
    data,
    page,
    size,
    total,
    queryData,
  }
}
